<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import PageContainer from '@/components/PageContainer.vue';
import {userUpdatePassService} from '@/api/user'
import { useUserStore } from '@/stores/modules/user';
import {useRouter} from 'vue-router'

//定义 store 和 router
const userStore=useUserStore()
const router=useRouter()
// 表单数据
const pwdForm = ref({
  old_pwd: '',
  new_pwd: '',
  re_pwd: ''
})

// 表单引用
const formRef = ref()

// 自定义校验：原密码和新密码不能一样
const validateNewPwd = (rule, value, callback) => {
  if (value === '') return callback(new Error('请输入新密码'))
  if (value.length < 6 || value.length > 15) return callback(new Error('密码长度应为6-15位'))
  if (value === pwdForm.value.old_pwd) {
    return callback(new Error('新密码不能与原密码相同'))
  }
  callback()
}

// 自定义校验：确认密码必须与新密码一致
const validateRePwd = (rule, value, callback) => {
  if (value === '') return callback(new Error('请确认密码'))
  if (value !== pwdForm.value.new_pwd) {
    return callback(new Error('两次密码输入不一致'))
  }
  callback()
}

// 校验规则
const rules = {
  old_pwd: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, max: 15, message: '密码长度应为6-15位', trigger: 'blur' }
  ],
  new_pwd: [{ validator: validateNewPwd, trigger: 'blur' }],
  re_pwd: [{ validator: validateRePwd, trigger: 'blur' }]
}

// 提交
const onSubmit = async () => {
   const valid = await formRef.value.validate()
  if (valid) {
    await userUpdatePassService(pwdForm.value)
    ElMessage({ type: 'success', message: '更换密码成功' })
    //清空当前 token 和当前用户信息
    userStore.setToken('')
    userStore.setUser({})
    //拦截路由
    router.push('/login')
  }
}

// 重置
const onReset = () => {
  formRef.value.resetFields()
}
</script>

<template>
<page-container   title="更换密码">
    <el-form
    :model="pwdForm"
    :rules="rules"
    ref="formRef"
    label-width="100px"
    style="max-width: 500px"
  >
    <el-form-item label="原密码" prop="old_pwd">
      <el-input v-model="pwdForm.old_pwd" show-password />
    </el-form-item>

    <el-form-item label="新密码" prop="new_pwd">
      <el-input v-model="pwdForm.new_pwd" show-password />
    </el-form-item>

    <el-form-item label="确认密码" prop="re_pwd">
      <el-input v-model="pwdForm.re_pwd" show-password />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="onSubmit">修改密码</el-button>
      <el-button @click="onReset">重置</el-button>
    </el-form-item>
  </el-form>
</page-container>
</template>